<template>
  <div>
    <el-dialog
      :title="info.isadd == true ? '商品添加' : '商品编辑'"
      :visible.sync="info.isshow"
      @closed="close"
      @opened="opened"
    >
      <el-form :model="form">
        <el-form-item label="一级分类" label-width="120px">
          <el-select
            v-model="form.first_cateid"
            placeholder="请选择"
            @change="change_first_cateid"
          >
            <el-option
              v-for="item in cateList"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类" label-width="120px">
          <el-select v-model="form.second_cateid" placeholder="请选择">
            <el-option
              v-for="item in second_cateid_list"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" label-width="120px">
          <el-input v-model="form.goodsname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="价格" label-width="120px">
          <el-input v-model="form.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="市场价格" label-width="120px">
          <el-input v-model="form.market_price" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="图片" label-width="120px">
          <!-- <div class="my-upload">
            <h3>+</h3>
            <img v-if="imgUrl" :src="imgUrl" alt />
            <input type="file" @change="changefile" />
          </div> -->
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imgUrl" :src="imgUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="商品规格" label-width="120px">
          <el-select
            v-model="form.specsid"
            placeholder="请选择"
            @change="change_specs_id"
          >
            <el-option
              v-for="item in specsList"
              :key="item.id"
              :label="item.specsname"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="规格属性" label-width="120px">
          <el-select v-model="form.specsattr" placeholder="请选择" multiple>
            <el-option
              v-for="item in attrsArr"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否新品" label-width="120px">
          <el-switch
            v-model="form.isnew"
            :active-value="1"
            :inactive-value="2"
          ></el-switch>
        </el-form-item>
        <el-form-item label="是否热卖" label-width="120px">
          <el-switch
            v-model="form.ishot"
            :active-value="1"
            :inactive-value="2"
          ></el-switch>
        </el-form-item>
        <el-form-item label="状态" label-width="120px">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="2"
          ></el-switch>
        </el-form-item>
        <el-form-item label="商品描述" label-width="120px">
          <div id="editor" v-if="info.isshow"></div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="info.isshow = false">取 消</el-button>
        <el-button type="primary" @click="add" v-if="info.isadd"
          >提交</el-button
        >
        <el-button type="primary" v-else @click="edit">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  reqcatelist,
  reqgoodsadd,
  reqgoodsinfo,
  reqgoodsedit,
} from "../../../request/api";
import { successAlert, errorAlert } from "../../../utils/alert";
import { mapActions, mapGetters } from "vuex";
import path from "path";
import E from "wangeditor";
export default {
  props: ["info"],
  data() {
    return {
      form: {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: null,
        description: "",
        specsid: "",
        specsattr: [],
        isnew: 1,
        ishot: 1,
        status: 1,
      },
      second_cateid_list: [],
      attrsArr: [],
      imgUrl: "",
    };
  },
  methods: {
    ...mapActions({
      reqList: "goods/reqList",
      reqCateList: "cate/reqList",
      reqTotal: "goods/reqTotal",
      reqSpecsList: "specs/reqList",
    }),
    change_first_cateid() {
      this.form.second_cateid = "";
      this.get_second_cate_list();
    },
    get_second_cate_list() {
      reqcatelist({ pid: this.form.first_cateid }).then((res) => {
        let list = res.data.list ? res.data.list : [];
        this.second_cateid_list = list;
      });
    },
    beforeAvatarUpload(file) {
      // console.log(e);
      // let file = e.target.files[0];
      console.log(file);
      let imgArr = [".png", ".jpg", ".jpeg", ".gif"];
      let extname = path.extname(file.name);
      console.log(extname);
      if (imgArr.indexOf(extname) == -1) {
        errorAlert("请上传正确的文件格式");
        return;
      }
      this.imgUrl = URL.createObjectURL(file);
      this.form.img = file;
    },
    change_specs_id() {
      this.form.specsattr = [];
      this.get_attrs_arr();
    },
    get_attrs_arr() {
      let obj = this.specsList.find((item) => item.id == this.form.specsid);
      this.attrsArr = obj ? obj.attrs : [];
    },
    opened() {
      this.editor = new E("#editor");
      this.editor.create();
      this.editor.txt.html(this.form.description);
    },
    changepid() {
      this.form.type = this.form.pid == 0 ? 1 : 2;
    },
    empty() {
      this.form = {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: null,
        description: "",
        specsid: "",
        specsattr: [],
        isnew: 1,
        ishot: 1,
        status: 1,
      };
      this.second_cateid_list = [];
      this.attrsArr = [];
      this.imgUrl = "";
      this.editor.txt.html(this.form.description);
    },

    add() {
      // console.log(this.cateList);
      this.form.description = this.editor.txt.html();
      reqgoodsadd({
        ...this.form,
        specsattr: this.form.specsattr.join(","),
      }).then((res) => {
        if (res.data.code == 200) {
          successAlert(res.data.msg);
          this.empty();
          // 3.弹框消失
          this.info.isshow = false;
          // 4.列表重新请求
          this.reqList();
          //请总数
          this.reqTotal();
        }
      });
    },

    getOne(id) {
      reqgoodsinfo({ id }).then((res) => {
        if (res.data.code == 200) {
          this.form = res.data.list;
          this.form.id = id;
          // 根据一级分类的id，请求二级分类list
          this.get_second_cate_list();
          //将form.specsattrs变成数组
          this.form.specsattr = this.form.specsattr.split(",");
          //根据specsid计算attrsArr
          this.get_attrs_arr();
          this.imgUrl = this.$api + this.form.img;

          //富文本编辑器赋值
          this.editor && this.editor.txt.html(this.form.description);
        }
      });
    },
    edit() {
      this.form.description = this.editor.txt.html();
      reqgoodsedit({
        ...this.form,
        specsattr: this.form.specsattr.join(","),
      }).then((res) => {
        if (res.data.code == 200) {
          successAlert(res.data.msg);
          this.empty();
          this.info.isshow = false;
          this.reqList();
        }
      });
    },
    close() {
      !this.info.isadd && this.empty();
    },
    addAttr() {
      this.attrArr.push({ value: "" });
    },
    attrDel(index) {
      this.attrArr.splice(index, 1);
    },
  },
  computed: {
    ...mapGetters({
      cateList: "cate/list",
      specsList: "specs/list",
    }),
  },
  mounted() {
    if (this.cateList.length == 0) {
      this.reqCateList();
    }
    this.reqSpecsList(true);
  },
};
</script>

<style scoped lang="less">
@import "../../../less/index.less";
.box {
  display: flex;
}
.box .el-input {
  flex: 1;
}
/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
// .my-upload {
//   width: 100px;
//   height: 100px;
//   border: 1px dashed @primary;
//   position: relative;
// }
// .my-upload h3 {
//   text-align: center;
//   height: 100px;
//   line-height: 100px;
//   color: @primary;
// }
// .my-upload input {
//   width: 100%;
//   height: 100%;
//   position: absolute;
//   left: 0;
//   top: 0;
//   opacity: 0;
// }
// .my-upload img {
//   width: 100%;
//   height: 100%;
//   position: absolute;
//   left: 0;
//   top: 0;
// }
</style>
